const express = require('express');
const mongoose = require('mongoose');
const VCode = require('./models/vCode.js');
const User = require('./models/user.js');
const Key = require('./models/key.js');
const utils = require('./utils/utils.js');
const NodeRSA = require('node-rsa');
const CryptoJS = require('crypto-js');
const asyncUtil = require('express-async-handler');
const svgCaptcha = require('svg-captcha');
const cookieParser = require('cookie-parser');
const app = express();
const port = 80;

const userRouter = require('./routers/userRouter.js');

const vCodeTime = 3 * 60 * 1000;//3分钟

app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cookieParser());

app.use('/user', userRouter);

app.get("/vCode", asyncUtil(async (req, res) => {
  const captcha = svgCaptcha.create({
    noise: 4,
    background: "#cc9966",
    height: 38,
    width: 60,
    fontSize: 38
  });

  const r = await new VCode({code: captcha.text}).save();

  setTimeout(async () => {
    await VCode.findByIdAndDelete(r._id.toString());
  }, vCodeTime);

  res.json(utils.success({code: captcha.data, id: r._id}));
}));

app.use((err, req, res, next) => {
  if (err) {
    console.error(err);
    res.json({success: false, msg: err.message})
  }
});

app.listen(port, () => {
  console.log("server start on: http://127.0.0.1");

  //连接数据库
  mongoose.connect('mongodb://admin:111111@192.168.0.149:27017/testdb').then(() => {
    console.log('db connected !!!')

    //添加默认的超级管理员
    User.findOne({$where: 'this.roles !== undefined && this.roles.includes("superAdmin")'})
      .then(r => {
        if (r === null) {
          let pwd = CryptoJS.AES.encrypt('111111', 'li');

          new User({
            account: "superAdmin",
            pwd,
            nickname: '超级管理员',
            roles: ["superAdmin", "admin", "user"]
          }).save().then(_r => {
            let key = new NodeRSA({b: 512});
            key.generateKeyPair(2048, 65537);
            const pk = key.exportKey('pkcs1-public');
            const sk = key.exportKey('pkcs1-private');
            new Key({
              pk, sk,
              uId: _r._id.toString()
            }).save()
          })
        }
      });
  });


  mongoose.connection.on('error', err => {
    console.error(err);
  });
});

function decryptRSA(k, buffer) {
  const rsa = new NodeRSA({b: 512});
  rsa.importKey(k.pk, 'pkcs1-public');
  rsa.importKey(k.sk, 'pkcs1-private');
  let r = rsa.decrypt(Buffer.from(buffer.data));
  return r.toString();
}
